﻿using FrameworkCore.Constants;
using FrameworkCore.Extensions;
using FrameworkCore.Repositories;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace FrameworkCore.DI;

/// <summary>
/// 自动依赖注入服务
/// </summary>
public static class DependencyInjectionServices
{
    /// <summary>
    /// 扫描程序集并注册服务
    /// </summary>
    /// <param name="services"></param>
    /// <returns></returns>
    public static IServiceCollection AddDependencyInjectionServices(this IServiceCollection services)
    {
        #region 扫描程序集       
        var baseType = typeof(IDependency);
        var path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
        var assemblyFiles = Directory.GetFiles(path, GlobalConstants.AssemblySuffix);

        var modulePath = ApplicationPartManagerExtensions.GetModulesDirectory();
        if (!string.IsNullOrWhiteSpace(modulePath))
        {
            var moduleAssemblyFiles = Directory.GetFiles(modulePath, GlobalConstants.AssemblySuffix);
            assemblyFiles = assemblyFiles.Concat(moduleAssemblyFiles).ToArray();
        }

        var filteredAssemblyFiles = assemblyFiles.Where(file => !file.Contains("System.") && !file.Contains("Microsoft."));
        var referencedAssemblies = filteredAssemblyFiles.Select(Assembly.LoadFrom).ToList();
        #endregion

        #region 获取继承IDependency对象
        var types = referencedAssemblies
            .SelectMany(a => a.DefinedTypes)
            .Select(type => type.AsType())
            .Where(x => baseType.IsAssignableFrom(x)
            && (x != baseType)
            && !(x == typeof(IScopedDependency)
            || x == typeof(ISingletonDependency)
            || x == typeof(ITransientDependency)))
            .ToList();
        #endregion

        #region 注册服务
        var implementTypes = types.Where(x => x.IsClass).ToList();
        var interfaceTypes = types.Where(x => x.IsInterface).ToList();
        foreach (var implementType in implementTypes)
        {
            if (typeof(IScopedDependency).IsAssignableFrom(implementType))
            {
                var interfaceType = interfaceTypes.FirstOrDefault(x => x.IsAssignableFrom(implementType));
                if (interfaceType != null)//继承接口的注入
                    services.AddScoped(interfaceType, implementType);
                else //无继承接口的注入
                    services.AddScoped(implementType);
            }
            else if (typeof(ISingletonDependency).IsAssignableFrom(implementType))
            {
                var interfaceType = interfaceTypes.FirstOrDefault(x => x.IsAssignableFrom(implementType));
                if (interfaceType != null)//继承接口的注入
                    services.AddSingleton(interfaceType, implementType);
                else//无继承接口的注入
                    services.AddSingleton(implementType);
            }
            else
            {
                var interfaceType = interfaceTypes.FirstOrDefault(x => x.IsAssignableFrom(implementType));
                if (interfaceType != null)//继承接口的注入
                    services.AddTransient(interfaceType, implementType);
                else//无继承接口的注入
                    services.AddTransient(implementType);
            }
        }
        #endregion

        return services;
    }
}
